<template>
  <view class="animated fadeIn faster ">
    <view class="searchBox px-2 rounded20 d-flex-item d-flex d-flex-middle bg-fff mt-2 mx-2">
      <input v-model="formData.name" class="pl-1 rounded10 font30 d-flex-item" placeholder="搜索订单"
             placeholder-class="colorhold"/>
      <text v-if="formData.name" class="text-right iconfont icon-cuo1 main-color ml-1"
            @click="dataCancel"></text>
      <text class="iconfont icon-icon_sousuo main-color font40  text" @click="onSearch"></text>
    </view>

    <scroll-view
        class="tab-scroll-container pt-2"
        scroll-x="true"
        :scroll-left="scrollLeft"
        scroll-with-animation
    >
      <view class="d-flex font28 tab-scroll_box d-flex-around bg-fff py-2 main-color">
        <!-- 选项卡类别列表 -->
        <view v-for="(item,index) in tabList" :key="index" :class="{'active':isActiveList===item.id}"
              class="tab-scroll_item " @click="chenkedList(item.id, index)">
          {{ item.name }}
        </view>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <view class="order-list px-2 pt-2">

      <scroll-view
          scroll-y
          refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @scrolltolower="onScrollToLower"
          refresher-background="#f5f5f5"
          class="scroll-area"
          style="height: calc(100vh - 250rpx);"
      >
        <view v-if="orderList.length > 0">
          <view

              v-for="(order, index) in orderList"
              :key="order.id"
              class="order-item bg-fff rounded10 p-3 mb-2"
          >
            <!-- 订单头部：订单编号和状态 -->
            <view class="order-header d-flex d-flex-between d-flex-middle pb-2">
              <text class="font28 color-5C5C5C">订单编号：{{ order.order_no }}</text>
              <text class="font28" :class="getStatusClass(order.status)">
                {{ getStatusText(order.status) }}
              </text>
            </view>

            <!-- 订单内容：商品信息 -->
            <view class="order-content d-flex d-flex-bottom">
              <image
                  :src="order.course_image "
                  class="order-image rounded10"
                  mode="aspectFill"
              ></image>
              <view class="ml-3 d-flex-item">
                <view class="font28 text-clamp-two">{{ order.category_name }}</view>
                <view class="font24 color999 mt-1">{{ order.full_category_name }}</view>
                <view class="font24 color999 mt-1">{{ order.created_at }}</view>
              </view>
              <view class="d-flex d-flex-column text-right">
                <view class="font30 font-bold colorf00">
                  <text class="font20">¥</text>
                  {{ order.amount }}
                </view>
                <view v-if="order.status ==1"
                      class="ml-5 mt-2 py-1 rounded30 px-2 colorfff font26 bg-main d-flex-item text-center"
                      @click="goUrl(`/subPages/orderConfirmation/orderConfirmation?order=${encodeURIComponent(JSON.stringify(
                  order))}`)">去付款
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="load-more d-flex d-flex-center d-flex-column d-flex-middle py-4"
              v-if="loadingType >= 1 && orderList.length == 0">
          <image
              src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png"
              style="width: 198rpx;height: 128rpx;margin-top: 260rpx;"></image>
          <text class="empty-text">{{ loadingType === 1 ? '正在加载...' : '~ 暂无相关订单 ~' }}</text>
        </view>
      </scroll-view>
    </view>

  </view>
</template>

<script>
import {mapState} from "vuex"
import {payApi} from "@/http/payApi";

export default {
  data() {
    return {
      formData: {
        name: ''
      },
      tabList: [
        {id: '', name: '全部'},
        {id: 1, name: '待支付'},
        {id: 2, name: '已支付'},
        {id: 3, name: '已取消'},
        // {id: 4, name: '售后'}
      ],
      isActiveList: 1,
      scrollLeft: 0,
      sWidth: 0,
      orderList: [], // 订单列表数据
      loading: false,
      refreshing: false, // 下拉刷新状态
      loadingType: 1,
      page: 1
    }
  },
  onShow() {
    this.loadingType = 1
    this.orderList=[]
    this.page=1
    this.goOrder()
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
    }),
  },
  methods: {
    async goOrder() {
      let that = this
      that.loadingType = 1
      try {
        let params = {
          page: this.page,
          status: this.isActiveList,
          keyword: this.formData.name
        }
        let result = await payApi.orderUserList(params)
        if (result.orders) {
          that.orderList = that.orderList.concat(result.orders)
        }
        if (result.orders && result.orders.length > 9) {
          that.loadingType = 0
        } else {
          that.loadingType = 2
        }
      } catch (error) {
        that.loadingType = 2
      }
    },
    // 下拉刷新处理
    async onRefresh() {
      if (this.refreshing) return;

      this.refreshing = true;
      this.loadingType = 1; // 设置加载状态
      this.orderList = [];
      this.page = 1;
      try {
        await this.goOrder(this.isActiveList);
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      } finally {
        this.refreshing = false;
        if (this.orderList.length === 0) {
          this.loadingType = 2; // 确保无数据时显示正确状态
        }
      }
    },
    dataCancel() {
      this.formData.name = '';
      setTimeout(()=>{
        this.goOrder();
      },600)
    },

    onSearch() {
      this.page = 1
      this.orderList = [] // 搜索时清空列表
      this.goOrder(); // 执行搜索
    },

    chenkedList(id, index) {
      this.isActiveList = id;
      this.page = 1
      this.orderList = []
      // 根据选中的选项卡加载对应订单数据
      this.goOrder();
    },

    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '等待支付',
        2: '已支付',
        3: '已取消',
        4: '已完成',
        5: '售后中'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        1: 'color-warning', // 等待支付 - 橙色
        2: 'color-success', // 已支付 - 绿色
        3: 'color-gray', // 已完成 - 灰色
        4: 'color-success',    // 已取消 - 绿色
        5: 'color-info'     // 售水中 - 蓝色
      };
      return classMap[status] || '';
    },
    // 取消订单
    async cancelOrder(orderId) {
      uni.showModal({
        title: '提示',
        content: '确认取消该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await fileApi.cancelOrder({id: orderId});
              uni.showToast({
                title: '取消成功',
                icon: 'success'
              });
              this.goOrder(); // 刷新订单列表
            } catch (error) {
              uni.showToast({
                title: '取消失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 去付款
    payOrder(orderId) {
      // 跳转到支付页面
      uni.navigateTo({
        url: `/subPages/payment/payment?orderId=${orderId}`
      });
    },

    // 申请退款
    applyRefund(orderId) {
      uni.navigateTo({
        url: `/subPages/refund/apply?orderId=${orderId}`
      });
    },

    // 删除订单
    async deleteOrder(orderId) {
      uni.showModal({
        title: '提示',
        content: '确认删除该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await fileApi.deleteOrder({id: orderId});
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              this.goOrder(); // 刷新订单列表
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    onScrollToLower() {
      if (this.loadingType == 2 || this.loadingType == 1) {
        return;
      }
      this.page++
      this.goOrder();
    }
  },

}
</script>

<style scoped>.searchBox {
  background-color: #fff;
  height: 80rpx;
  line-height: 80rpx;
}

.searchBox input {
  height: 100%;
}

.tab-scroll-container {
  width: 100%;
  white-space: nowrap;
  position: relative;
}

.tab-scroll_box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  box-sizing: border-box;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.tab-scroll_item {
  display: flex;
  justify-content: center;
  white-space: nowrap;
  padding: 0 20rpx;
}

.active {
  position: relative;
  font-weight: 600;
  text-decoration: underline
}

.active::after {
  content: "";
  position: absolute;
  width: 50rpx;
  height: 4rpx;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
}

/* 订单列表样式 */
.order-image {
  width: 120rpx;
  height: 120rpx;
  background: #e1e1e1;
  flex-shrink: 0;
}

.border-top {
  border-top: 1rpx solid #f0f0f0;
}

.action-btn {
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  font-size: 26rpx;
}

.pay-btn {
  background: linear-gradient(90deg, #007AFF, #218bfd);
  color: white;
  border: none;
}

.cancel-btn, .refund-btn, .delete-btn {
  border: 1rpx solid #ddd;
  background: white;
  color: #333;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
}

.color-warning {
  color: #ff9900;
}

.color-success {
  color: #00cc66;
}

.color-gray {
  color: #999999;
}

.color-info {
  color: #007AFF;
}
</style>